﻿$(function() {
    try {
        getComments(contentId);
    } catch(error) {

    }

    var anchor = $('#anchor');
    $(window).on('scroll', function() {
        var sidebar = $('#sidebar');
        var winWidth = $(window).innerWidth();
        if($(window).scrollTop() >= 650 && winWidth > 1080) {
            // sidebar.find('.bar').addClass('fixed');
            anchor.css('display', 'block');
        } else {
            // sidebar.find('.bar').removeClass('fixed');
            anchor.css('display', 'none');
        }

    });

    $(window).on('resize', function() {
        var winWidth = $(window).innerWidth();

        if(winWidth < 1080) {
            anchor.css('display', 'none');
        } else {
            anchor.css('display', 'block');
        }
    })

    anchor.on('click', function() {
        $("html, body").animate({ scrollTop: 0 });
    });

    $('#zoom').on('click', 'a', function() {
        var size = parseInt($(this).attr('data-size'));
        $('.content p').css('fontSize', size + 'px');
    });

    $('#comments-count').on('click', function() {
        scrollToView($('#comments'));
    });

    $('#comments').on('click', '.link-btn', function() {
        var btn = $(this);
        var opt = btn.attr('data-opt');
        var commentId = btn.parents('.comment').attr('data-id');
        if(!checkLogin()) return;
        switch(opt) {
            case 'report':
                var offset = btn.offset();
                var report = $('#report');

                report.fadeIn()
                    .attr('data-id', commentId)
                    .offset({
                        'top': offset.top + 22,
                        'left': offset.left - 320
                    });
                break;
            case 'agree':
                var approved = btn.parents('.comment').attr('data-approved');

                if(approved == true || approved == 'true') {
                    // showMessage('不能重复点赞');
                    return;
                }
                agree.call(btn, commentId);
                break;
            case 'reply':
                var reply = $('#reply');
                reply.attr('data-refId', commentId);
                scrollToView(reply);
                break;
        }
    })

    $('#report').on('click', '.icon.icon-close,#report-cancel', function() {
        var report = $('#report');
        report.fadeOut();
    });

    $('#reply textarea').on('propertychange change keyup paste input', function() {
        var textarea = $(this);
        var len = textarea.val().length;
        var val = textarea.val()

        if(len > 200) {
            textarea.val(val.substr(0, 200));
            return false;
        }
    });

    $('#report-submit').on('click', function() {
        var commentId = $('#report').attr('data-id');
        var comment = $('.comment[data-id="' + commentId + '"]');
        var status = $("#report input[name='reason']:checked").val();
        report(commentId, status, comment);
    });

    $('.comments-wrapper').on('click', '.more', function() {
        var more = $(this);
        if(more.hasClass('loading')) return;

        more.addClass('loading').text('加载中');
        getComments(contentId, lastId);
    });

    $('#btn-submit').on('click', function() {
        var txt = $('#reply').find('textarea').val();
        var refId = $('#reply').attr('data-refId');
        checkLogin();
        if(!txt.length) return;
        submitComment(txt, refId);

    });

    $('.main-container').on('click', '.message .icon.icon-close', function() {
        $('.message').fadeOut().remove();
    });

});

function checkLogin() {
    if(!isLogin) {
        $('#J_dota2SignIn').trigger('click');
        return false;
    }
    return true;
}

function getComments(contentId, start) {
    var conmentsContainer = $('#comments');
    start = start || 0;
    $.ajax({
        url: '/comments?task=getList&start=' + start + '&contentId=' + contentId,
        method: 'GET',
        data: {},
    }).done(function(r) {
        var result = JSON.parse(r);
        if(result.status === 'success') {
            lastId = result.data.lastId;

            var data = result.data.comments;
            var total = result.data.total;
            var len = data.length;
            var comments = [];
            var btnMore = $('#more');

            $('#comments-count>em').text(total);
            $('#reply .reply-title').find('em').text(total);
            for(var i = 0; i < len; i++) {
                var comment = generateComment(data[i]);
                comments.push(comment);
            }

            if(start) {
                conmentsContainer.append($(comments.join('')));
            } else {
                conmentsContainer.html(comments.join(''));
            }

            if(len == 5) {
                if(!btnMore.length) {
                    btnMore = $('<div class="more" id="more"><p>加载更多</p></div>');
                    btnMore.insertAfter(conmentsContainer);
                } else {
                    btnMore.removeClass('loading').text('加载更多');
                }
            } else {
                btnMore.remove();
            }
        }
    })
}

function generateComment(data) {
    var reply = '';
    var comment;

    if(data['replyComment']) {
        if(data['replyComment']['nickname']) {
            reply = '<div class="body-sub"><p class="name">' + data['replyComment']['nickname'] + '</p><p>' + data['replyComment']['comment'] + '</p></div>';
        } else {
            reply = '<div class="body-sub"><p>' + data['replyComment']['comment'] + '</p></div>';
        }
    }

    comment = [
        '<div class="comment clearfix" data-id="' + data['id'] + '"  data-approved="' + data['approved'] + '">',
        '<div class="avatar"><img src="' + data['headicon'] + '" alt="头像"/></div>',
        '<div class="comment-body">',
        '<div class="body-header">',
        '<span class="name">' + data['nickname'] + '</span>',
        '<span class="date">' + data['timeDes'] + '</span>',
        '<div class="btns">',
        '<a href="javascript:void(0)" class="link-btn btn-report" data-opt="report"><i class="icon icon-report"></i><span>举报</span></a>',
        '<a href="javascript:void(0)" class="link-btn btn-agree" data-opt="agree"><i class="icon icon-agree"></i><span>(' + data['approveNumber'] + ')</span></a>',
        '<a href="javascript:void(0)" class="link-btn btn-reply" data-opt="reply"><i class="icon icon-replay"></i>回复</a>',
        '</div></div>',
        '<div class="body-content"><p>' + data['comment'] + '</p></div>',
        reply,
        '</div></div>'
    ];

    return comment.join('');
}

function agree(id) {
    var btn = this;
    var url = '/comments?task=zan&commentId=' + id;
    $.post(url, function(r) {
        var result = JSON.parse(r);
        if(result.status == 'success') {
            var span = btn.find('>span');
            var count = span.text().replace(/[()]/g, '');
            count = parseInt(count, 10);
            span.text('(' + (count + 1) + ')');
            btn.parents('.comment').attr('data-approved', true);
        } else {
            showMessage('点赞失败，请重试。');
        }
    });
}

function report(id, status, comment) {
    var btn = comment.find('>.link-btn.btn-report');
    var url = '/comments?task=report&commentId=' + id + '&status=' + status;
    $.post(url, function(r) {
        var result = JSON.parse(r);
        if(result.status == 'success') {
            var span = btn.find('>span');
            span.text('该评论已被您举报');
            $('#report').fadeOut();
            showMessage('举报成功');
        }

        showMessage('举报成功');
    });
}

function submitComment(comment, refId) {
    var url;
    refId = refId || 0;
    url = '/comments?task=comment&comment=' + comment + '&contentId=' + contentId + '&refId=' + refId;
    $.post(url, function(r) {
        var result = JSON.parse(r);
        if(result.status == 'success') {
            var commentsContainer = $('#comments');
            var reply = $('#reply');
            var refId = reply.attr('data-refId');
            reply.find('textarea').val('');
            reply.attr('data-refId', '');
            getComments(contentId);
            scrollToView(commentsContainer);
        }
    });
}

function scrollToView(element) {
    var win = $(window);
    var scrollTop = win.scrollTop();
    var offset = element.offset();
    // element.get(0).scrollIntoView()

    $('html, body').animate({
        scrollTop: offset.top - 150
    }, 500);
}

function showMessage(message) {
    var messager = ' <div class="message"><div class="message-header clearfix"><h3>提示</h3><i class="icon icon-close"></i></div>' +
        '<div class="message-body"><p>' + message + '</p></div></div>';

    $(messager).appendTo($('.main-container'));
    setTimeout(function() {
        $('.message').fadeOut().remove();
    }, 2000);
}